package com.gmrz.uap.model;

import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.model.base.BaseAuthMetadata;
import com.gmrz.uap.util.Identities;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class AuthMetadata extends BaseAuthMetadata<AuthMetadata> {
    public static final AuthMetadata dao = new AuthMetadata();

    private static final String NAMESPACE = "authMetadata";
    private static final String SQL_SELECT_COMM = NAMESPACE + SystemConst._DEFAULT_SEPARATOR_DOT + "select_comm";
    private static final String SQL_SELECT_POLICYID = NAMESPACE + SystemConst._DEFAULT_SEPARATOR_DOT + "getAuthMetadataByPolicyId";
    private static final String SQL_SELECT_NON_POLICYID = NAMESPACE + SystemConst._DEFAULT_SEPARATOR_DOT + "getNonAuthMetadataByPolicyId";
    private static final String SQL_REMOVE_POLICYID_METADATAID = NAMESPACE + SystemConst._DEFAULT_SEPARATOR_DOT + "removeByPolicyIdAndMetadataId";

    /**
     * 根据AAID获取元数据信息
     *
     * @param aaid
     * @return
     */
    public AuthMetadata findByAAID(String aaid) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * FROM t_auth_metadata WHERE AAID = ?");
        AuthMetadata authMetadata = this.findFirst(sql.toString(), aaid);
        return authMetadata;
    }

    /**
     * 查询所有元数据
     *
     * @return
     */
    public List<AuthMetadata> findAll() {
        return dao.find("select metadata_id,aaid from t_auth_metadata");
    }

    /**
     * 根据页面传过来的条件进行分页查询
     *
     * @param authMetadata 元数据信息
     * @param page         页号
     * @param rows         行数
     * @param sort         排序字段
     * @param order        升序/降序
     * @return　分页结果 Page<AuthMetadata>
     */
    public Page<AuthMetadata> findList4Paginate(AuthMetadata authMetadata, int page, int rows, String sort, String order) {
        StringBuilder sql = new StringBuilder();

        sql.append("from t_auth_metadata where metadata_id=metadata_id ");

        Iterator<Map.Entry<String, Object>> i = authMetadata._getAttrsEntrySet().iterator();

        //循环遍历传过来的参数，并将参数拼接到SQL
        while (i.hasNext()) {
            Map.Entry<String, Object> obj = i.next();

            if (StrKit.isBlank(obj.getKey()))
                continue;

            if (StringUtils.equalsIgnoreCase("id", obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = " + obj.getValue());
                continue;
            }

            //如果数据为空或为NULL的时候，跳过此次循环进入下一次循环
            if (null == obj.getValue() || "" == obj.getValue()) {
                continue;
            }
            sql.append(" and " + obj.getKey() + " like '%" + obj.getValue() + "%'");

        }

        sql.append(" order by " + sort + " " + order);

        return this.paginate(page, rows, getSql(SQL_SELECT_COMM), sql.toString());
    }

    public boolean saveAuthMetadata(HashMap<String, String> authMetadataInfo) {
        String insertSql = "INSERT INTO t_auth_metadata (metadata_id,aaid, auth_version, description, json_data, status,auth_type) VALUES('" + Identities.uuid2() + "','" + authMetadataInfo.get("aaid") + "', " + authMetadataInfo.get("authVersion") + ", '" + authMetadataInfo.get("description") + "','" + authMetadataInfo.get("jsonData") + "', 1,'" + authMetadataInfo.get("auth_type") + "')";
        int update = Db.update(insertSql);
        return update > 0;
    }


    public List<AuthMetadata> getAuthMetadataByPolicyId(String policyId) {
        return this.find(getSql(SQL_SELECT_POLICYID), policyId);
    }

    public List<AuthMetadata> getNonAuthMetadataByPolicyId(Policy policy) {
        return this.find(getSqlPara(SQL_SELECT_NON_POLICYID, policy.getPlId(), policy.getAuthType()));
    }


    /**
     * 根据AAID获取元数据在策略中使用的数量
     *
     * @param metadataId 元数据ID
     * @return int 使用数量
     */
    public int getAuthMetadataUsingCountByMetadataId(String metadataId) {
        String sql = "select count(metadata_id) from t_policy_auth where metadata_id = ?";
        return Db.queryInt(sql, metadataId);
    }


    /**
     * 根据AAID获取元数据在认证数据中的数量
     *
     * @param metadataId 元数据ID
     * @return int 注册数量
     */
    public int getAuthMetadataRegisterUsingCountByMetadataId(String metadataId) {
        String sql = "select count(metadata_id) from t_authenticators where metadata_id = ?";
        return Db.queryInt(sql, metadataId);
    }

}
